package com.eastcom.common.db;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @since 2010
 * @author Dongping Mao
 */

public class Transaction extends AbstractTransaction{

	private Connection connection=null;
	
	private Session session=null;
	
	private boolean isClosed=false;
	
	private boolean isActive=false;
	
	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public boolean isClosed() {
		return isClosed;
	}

	public void setClosed(boolean isClosed) {
		this.isClosed = isClosed;
	}
	
	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}
	
	@Override
	public boolean isActive() {
		// TODO Auto-generated method stub
		return this.isActive;
	}
	
	@Override
	public void begin() throws Exception {
		// TODO Auto-generated method stub
		if(connection==null)
			throw new Exception("transaction is not active connection is null");
		
		if(connection.getAutoCommit()==true)
			connection.setAutoCommit(false);
		
		this.isActive=true;
	}

	@Override
	public void rollback(){
		try{
		    if(this.connection!=null){
			    this.connection.rollback();
			    this.isClosed=true;
			}
		}
		catch(SQLException e){
			e.printStackTrace();
		}
		finally{
		    this.session.removeCurrentTransaction();
		}
		
	}
	
	@Override
	public void commit() throws SQLException{
		if(this.connection!=null&&!connection.isClosed()){
			this.connection.commit();
			this.isClosed=true;
		}
		
		this.session.removeCurrentTransaction();
	}
	
	@Override
	public void close() throws SQLException{
		if(this.connection!=null){
			try{
			    this.session.recoverConnection(connection);
			}
			catch(Exception e){}
			
			this.connection.close();
			this.connection=null;
			this.isClosed=true;
			this.isActive=false;
		}
	}

}
